//
//  ViewController.m
//  1.9、UITableView分页
//
//  Created by 李坤 on 16/12/1.
//
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

//tableview对象
@property(nonatomic,strong)UITableView *tableView;
//数据源
@property(nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(@"%s",__func__);
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.frame = CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self loadMore];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    NSLog(@"%s",__func__);
    return self.dataSource.count+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%lu",indexPath.row);
    NSString *reusedStr = @"demo";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedStr];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedStr];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    if(indexPath.row == _dataSource.count){
        //定制最后一行的cell
        cell.textLabel.text = @"加载更多...";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor blueColor];
    }else{
        if((indexPath.row+1)%2==0){
            cell.textLabel.textColor = [UIColor redColor];
        }else{
            cell.textLabel.textColor = [UIColor blackColor];
        }
        
        //定制普通的cell
        cell.textLabel.text = self.dataSource[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"%s",__func__);
    if(indexPath.row == self.dataSource.count){
        [self loadMore];
        return;
    }
}

- (void)loadMore{
    dispatch_async(dispatch_get_main_queue(), ^{
        //添加数据
        if(!self.dataSource){
            self.dataSource = [NSMutableArray array];
        }
        [self.dataSource addObjectsFromArray:[self getData]];
        //重新加载tableview
        [self.tableView reloadData];
    });
}

- (NSMutableArray *)getData{
    static NSInteger page = 1;
    //第一步，创建URL
    NSURL *url = [NSURL URLWithString:@"http://api.yijiedai.com/invest"];
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSString *str = [NSString stringWithFormat:@"page=%lu",page];//设置参数
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //第三步，连接服务器
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
    NSArray<NSDictionary *> *dataList = result[@"data"][@"page"][@"dataList"];
//    NSLog(@"%@",dataList);
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *item in dataList) {
//        NSLog(@"%@",item);
        [array addObject:item[@"title"]];
    }
    page++;
    return array;
}

@end
